package com.shiwaixiangcun.customer.module.heath;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Parcelable;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.shiwaixiangcun.customer.GlobalApi;
import com.shiwaixiangcun.customer.GlobalConfig;
import com.shiwaixiangcun.customer.R;
import com.shiwaixiangcun.customer.base.BaseActivity;
import com.shiwaixiangcun.customer.entity.ResponseEntity;
import com.shiwaixiangcun.customer.entity.WeightBean;
import com.shiwaixiangcun.customer.event.EventUtil;
import com.shiwaixiangcun.customer.event.SimpleEvent;
import com.shiwaixiangcun.customer.network.StringDialogCallBack;
import com.shiwaixiangcun.customer.utils.AppSharePreferenceMgr;
import com.shiwaixiangcun.customer.utils.DateUtil;
import com.shiwaixiangcun.customer.utils.JsonUtil;
import com.shiwaixiangcun.customer.utils.LoginOutUtil;
import com.shiwaixiangcun.customer.utils.RefreshTokenUtil;
import com.shiwaixiangcun.customer.widget.ChangeLightImageView;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * 体重详情页面
 *
 * @author Administrator
 */
public class WeightActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.tv_weight_name)
    TextView mTvWeightName;
    @BindView(R.id.tv_weight_data)
    TextView mTvWeightData;
    @BindView(R.id.tv_weight_bmi)
    TextView mTvWeightBmi;
    @BindView(R.id.tv_weight_time)
    TextView mTvWeightTime;
    @BindView(R.id.ll_weight_back)
    LinearLayout mLlWeightBack;
    @BindView(R.id.tv_weight_zt)
    TextView mTvWeightZt;
    @BindView(R.id.tv_weight_introduce)
    TextView mTvWeightIntroduce;
    @BindView(R.id.tv_weight_dream)
    TextView mTvWeightDream;
    @BindView(R.id.textView)
    TextView mTextView;
    @BindView(R.id.textView2)
    TextView mTextView2;
    @BindView(R.id.rl_history_blood)
    RelativeLayout mRlHistoryBlood;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout mRefreshLayout;
    @BindView(R.id.back_left)
    ChangeLightImageView mBackLeft;
    @BindView(R.id.tv_page_name)
    TextView mTvPageName;
    @BindView(R.id.tv_top_right)
    TextView mTvTopRight;
    @BindView(R.id.iv_share_right)
    ImageView mIvShareRight;
    @BindView(R.id.iv_sao_right)
    ImageView mIvSaoRight;
    @BindView(R.id.ll_image_right)
    LinearLayout mLlImageRight;
    @BindView(R.id.top_bar_transparent)
    RelativeLayout mTopBarTransparent;
    @BindView(R.id.activity_blood_pressure)
    RelativeLayout mActivityBloodPressure;
    @BindView(R.id.chart_weight)
    LineChart mChartWeight;
    @BindView(R.id.llayout_chart)
    LinearLayout mLlayoutChart;


    private List<WeightBean.ElementsBean> mWeightList;


    private Long customId = 0L;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weight);
        ButterKnife.bind(this);


        Bundle bundle = getIntent().getExtras();
        customId = bundle.getLong("customID");
        EventUtil.getInstance().register(this);
        layoutView();
        requestData();
        mWeightList = new ArrayList<>();


    }


    @Override
    protected void onRestart() {
        super.onRestart();
        requestData();
    }

    /**
     * 请求数据
     */
    private void requestData() {
        final String refreshToken = (String) AppSharePreferenceMgr.get(mContext, GlobalConfig.Refresh_token, "");
        String tokenString = (String) AppSharePreferenceMgr.get(mContext, GlobalConfig.TOKEN, "");
        OkGo.<String>get(GlobalApi.INSTANCE.getGetWeight())
                .params("access_token", tokenString)
                .params("customerId", customId)
                .params("page.pn", 1)
                .params("page.size", 7)
                .execute(new StringDialogCallBack(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Type type = new TypeToken<ResponseEntity<WeightBean>>() {
                        }.getType();
                        ResponseEntity<WeightBean> responseEntity = JsonUtil.fromJson(response.body(), type);
                        if (responseEntity == null) {
                            return;
                        }
                        switch (responseEntity.getResponseCode()) {
                            case 1001:

                                WeightBean.ElementsBean elementsBean = responseEntity.getData().getElements().get(0);
                                EventUtil.getInstance().post(new SimpleEvent(SimpleEvent.UPDATE_WIGHT, 1, elementsBean));

                                mWeightList.clear();
                                mWeightList.addAll(responseEntity.getData().getElements());

                                initChart(mWeightList);
                                break;
                            case 1018:
                                RefreshTokenUtil.refreshToken(mContext, refreshToken);
                                break;
                            case 1019:
                                LoginOutUtil.sendLoginOutUtil(mContext);
                                break;
                            default:
                                break;
                        }
                    }

                });

    }

    private void initChart(List<WeightBean.ElementsBean> weightList) { //坐标点
        setChart(mChartWeight);

        ArrayList<Entry> mListWeight = new ArrayList<>();


        if (weightList.size() < 2) {
            mLlayoutChart.setVisibility(View.GONE);
        }
        int size = weightList.size();
        for (int i = 0; i < size; i++) {
            WeightBean.ElementsBean elementsBean = weightList.get(size - i - 1);
            mListWeight.add(new Entry(i + 1, (float) elementsBean.getWeight()));
        }
        LineDataSet mSetWeight = new LineDataSet(mListWeight, "体重");
        setAxis(mChartWeight, mListWeight, 73.0f, 45.5f);
        setDataToChart(mSetWeight, mChartWeight);


    }

    /**
     * 设置Chart
     *
     * @param chart
     */
    private void setChart(LineChart chart) {
        chart.getDescription().setEnabled(false);
        chart.setTouchEnabled(true);
        chart.setDragDecelerationFrictionCoef(0.9f);
        chart.setDragEnabled(true);
        chart.setScaleEnabled(true);
        chart.setDrawGridBackground(false);
        chart.setHighlightPerDragEnabled(false);
        chart.setPinchZoom(false);
        chart.setBackgroundColor(Color.WHITE);
    }


    /**
     * 设置图表的坐标轴
     *
     * @param chart           图表控件
     * @param mRelaxationList 图表坐标点数据
     * @param max             Y轴最大值
     * @param min             Y轴最小值
     */

    private void setAxis(LineChart chart, ArrayList<Entry> mRelaxationList, float max, float min) {
        //初始化Y轴
        YAxis yAxis = chart.getAxisLeft();
        yAxis.setDrawGridLines(true);
        yAxis.isDrawBottomYLabelEntryEnabled();
        yAxis.setAxisLineColor(R.color.black_text_40);
        yAxis.setAxisMaximum(max);
        yAxis.setAxisMinimum(min);
        yAxis.setDrawAxisLine(true);
        yAxis.setDrawZeroLine(true);
        yAxis.setZeroLineColor(R.color.black_text_40);
        yAxis.enableGridDashedLine(10f, 10f, 0f);
        chart.getAxisRight().setEnabled(false);


        //设置X轴
        XAxis xAxis = chart.getXAxis();
        xAxis.setAxisLineColor(R.color.black_text_40);
        xAxis.setAxisMaximum(mRelaxationList.size() > 8 ? 10 : mRelaxationList.size() + 1);
        xAxis.setAxisMinimum(0f);
        xAxis.setXOffset(1f);
        xAxis.enableGridDashedLine(10f, 10f, 0f);
        xAxis.setDrawGridLines(true);
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
    }

    /**
     * 给图表设置数据
     *
     * @param dataSet 数据集
     * @param chart   图表控件
     */
    private void setDataToChart(LineDataSet dataSet, LineChart chart) {
        dataSet.setAxisDependency(YAxis.AxisDependency.LEFT);
        dataSet.setColor(Color.parseColor("#1CCC8C"));
        dataSet.setCircleColor(Color.parseColor("#1CCC8C"));
        dataSet.setLineWidth(2f);
        dataSet.setCircleRadius(4f);
        dataSet.setFillAlpha(65);
        LineData data = new LineData(dataSet);
        data.setValueTextColor(R.color.black_text_60);
        data.setValueTextSize(10f);

        // set data

        chart.setData(data);
        chart.invalidate();
    }

    private void layoutView() {
        mBackLeft.setOnClickListener(this);
        mRlHistoryBlood.setOnClickListener(this);


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateUI(SimpleEvent simpleEvent) {
        if (simpleEvent == null || simpleEvent.mEventType != SimpleEvent.UPDATE_WIGHT) {
            return;
        }
        WeightBean.ElementsBean elementsBean = (WeightBean.ElementsBean) simpleEvent.getData();
        String healthStatus = elementsBean.getHealthStatus();
        String statusEnum = elementsBean.getStatusEnum();
        setBackground(healthStatus, statusEnum);

        mTvWeightData.setText(elementsBean.getWeight() + "");
        mTvWeightBmi.setText(elementsBean.getBmi() + "");
        mTvWeightTime.setText(DateUtil.INSTANCE.getSecond(elementsBean.getCreateTime()));
        mTvWeightDream.setText(elementsBean.getWeightDream() + "");
        mTvWeightIntroduce.setText(elementsBean.getSuggestion());
        Log.e(BUG_TAG, elementsBean.getSuggestion());

    }

    /**
     * 设置头部颜色
     *
     * @param healthStatus 状态
     */
    private void setBackground(String healthStatus, String statusEnum) {
        switch (healthStatus) {
            case "NORMAL":
                mLlWeightBack.setBackground(getResources().getDrawable(R.drawable.shape_green_gradient));
                break;
            case "WARNING":
                mLlWeightBack.setBackground(getResources().getDrawable(R.drawable.shape_yellow_gradient));

                break;
            case "DANGER":
                mLlWeightBack.setBackground(getResources().getDrawable(R.drawable.shape_red_gradient));
                break;
            default:
                break;

        }
        switch (statusEnum) {
            case "Zhengchang":
                mTvWeightName.setText("体重正常");
                mTvWeightZt.setText("您的体重正常");
                mTvWeightZt.setTextColor(Color.parseColor("#15B77C"));
                break;
            case "Piangao":
                mTvWeightName.setText("偏胖");
                mTvWeightZt.setText("您的身体偏胖");
                mTvWeightZt.setTextColor(Color.parseColor("#F96B21"));
                break;
            case "Paindi":
                mTvWeightName.setText("偏瘦");
                mTvWeightZt.setText("您的身体偏瘦");
                mTvWeightZt.setTextColor(Color.parseColor("#F96B21"));
                break;
            case "Yzpiangao":
                mTvWeightName.setText("肥胖");
                mTvWeightZt.setText("你的身体肥胖");
                mTvWeightZt.setTextColor(Color.parseColor("#D53635"));
                break;
            default:
                break;
        }
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id) {
            case R.id.back_left:
                finish();
                break;
            case R.id.rl_history_blood:
                Bundle bundle = new Bundle();
                bundle.putParcelableArrayList("blood_history", (ArrayList<? extends Parcelable>) mWeightList);
                readyGo(WeightHistoryActivity.class, bundle);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        EventUtil.getInstance().unregister(this);
    }
}